<template>
  <page-card title="角色授权"
             :need-back="true"
             :sub-title="name">
    <a-row type="flex"
           :gutter="16">
      <a-col :span="6">
        <a-card class="left-role-box"
                title="机构树"
                :bodyStyle="{height:'650px',overflowY: 'scroll'}">
          <div style="width:100%; overflow-x:auto">
            <slot name="unitTree" />
            <template v-if="!$slots.unitTree">
              <a-form layout="inline">
                <a-row>
                  <a-col :span="24">
                    <a-input-search placeholder="机构名称、编码"
                                    v-model="unitNameOrCode"
                                    @search="findUnit"
                                    style="min-width:200px;width: 100%"
                                    allow-clear />
                  </a-col>
                </a-row>
              </a-form>
              <a-table v-if="!showtree"
                       bordered
                       ref="unitTableList"
                       :showHeader="false"
                       :pagination="unitpagination"
                       :rowKey="(record, index) => record.id"
                       :data-source="unitdata"
                       :customRow="unitTableRowClick"
                       @change="unitHandleTableChange"
                       :columns="unitcolumns">
                <template slot="cfullName"
                          slot-scope="text,record"
                          :algin="left">
                  <div style="cursor: pointer;"
                       :title="record.parentName +'/'+record.fullName">
                    <span v-if="!!record.parentName">{{ record.parentName }}<span>&nbsp;/&nbsp;</span></span>{{ record.fullName }}
                  </div>
                </template>
              </a-table>
              <a-tree style="overflow-y: auto;height: 650px;"
                      v-if="showtree"
                      :replace-fields="unitReplaceFields"
                      :showIcon="true"
                      class="treeClass"
                      :load-data="loadUnitTree"
                      :tree-data="unitTreeData"
                      @select="selectUnit">
                <a-icon slot="switcherIcon"
                        type="caret-down" />
                <a-icon slot="clazz"
                        type="appstore" />
                <a-icon slot="unit"
                        type="home" />
                <a-icon slot="dept"
                        type="bank" />
              </a-tree>
            </template>
          </div>
        </a-card>
      </a-col>
      <a-col :span="9">
        <a-card title="人员列表"
                :bodyStyle="{height:'650px'}">
          <a slot="extra"
             href="#"
             @click="batchSaveList">全部添加</a>
          <div style="padding-bottom:20px">
            <a-input-search v-model="queryParam.keyWord"
                            placeholder="用户姓名、账号"
                            allow-clear
                            @search="userloadAll" />
          </div>
          <a-table :columns="usercolumns"
                   ref="userTableList"
                   :rowKey="(record, index) => record.id"
                   :data-source="userdata"
                   class="userTableListCheck"
                   @change="userHandleTableChange"
                   :pagination="userpagination">
            <template slot="userName"
                      slot-scope="text,record">
              <span :title="record.fullname">{{ record.fullname }} ({{ record.account }})</span>
            </template>
            <template slot="unitName"
                      slot-scope="text,record">
              <a-tooltip :title="record.belongs || record.deptName">
                <span>
                  {{ record.belongs || record.deptName }}
                </span>
              </a-tooltip>
            </template>
            <template slot="state"
                      slot-scope="text,record">
              <span style="color:#1890ff;cursor:pointer;"
                    @click="batchSaveStr(record.id)">添加</span>
            </template>
          </a-table>
        </a-card>
      </a-col>
      <a-col :span="9">
        <a-card title="选中人员"
                :bodyStyle="{height:'650px'}">
          <a slot="extra"
             href="#"
             @click="batchRemoveList">全部移除</a>
          <div style="padding-bottom:20px">
            <a-input-search v-model="queryParamList.keyWord"
                            placeholder="用户姓名、账号"
                            allow-clear
                            @search="userloadAllList" />
          </div>
          <a-table :columns="usercolumns"
                   ref="userTableList"
                   :rowKey="(record, index) => record.id"
                   :data-source="userdataList"
                   @change="userHandleTableChangeList"
                   :pagination="userpaginationList">
            <template slot="userName"
                      slot-scope="text,record">
              <span :title="record.fullname">{{ record.fullname }} ({{ record.account }})</span>
            </template>
            <template slot="unitName"
                      slot-scope="text,record">
              <a-tooltip :title="record.belongs || `${record.unitName}-${record.deptName}`">
                <span>
                  {{ record.belongs || `${record.unitName}-${record.deptName}` }}
                </span>
              </a-tooltip>
            </template>
            <template slot="state"
                      slot-scope="text,record">
              <span style="color:#1890ff;cursor:pointer;"
                    @click="batchRemoveStr(record.id)">移除</span>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>

  </page-card>
</template>
<script>

import { queryUnit, saveUnit, getUserIds, getRoleUnitUserListPage, getRoleUnitUserNotInListPage, batchSave, batchRemove } from '../../api/role/index'
import { unitpage, syncUnitTree } from '../../api/user/index'
import { unitTreeByIsTest } from '../../api/unit'
export default {
  data () {
    return {
      roleData: {},
      dataList: [],
      checkedKeysUnit: {
        checked: [],
        halfChecked: []
      },
      unitTreeData: [],
      unitReplaceFields: { title: 'treeTitle' },
      checkStrictly: true,
      name: this.$route.query.name,
      expandedKeys: [],
      treeDataUnit: [],
      selectedKeys: [],
      autoExpandParent: true,
      searchValue: '',
      unitdata: [],
      showtree: true,
      unitSearch: '',
      userdata: [],
      userdataList: [],
      userIds: [],
      modalUnitVisible: false,
      modalUnitTitle: '',
      searchName: '',
      usercolumns: [
        {
          title: '姓名',
          dataIndex: 'userName',
          align: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'userName' },
          width: 120
        },
        {
          title: '机构名称',
          dataIndex: 'unitName',
          align: 'left',
          ellipsis: true,
          width: 200,
          scopedSlots: { customRender: 'unitName' }
        },
        {
          title: '操作',
          dataIndex: 'state',
          align: 'center',
          scopedSlots: { customRender: 'state' },
          width: 50
        }
      ],
      unitcolumns: [
        {
          title: '机构名称',
          dataIndex: 'name',
          align: 'left',
          ellipsis: true,
          scopedSlots: { customRender: 'cfullName' }
        }
      ],
      appId: '',
      queryParam: {
        secrehUnitId: '',
        unitId: '',
        keyWord: ''
      },
      queryParamList: {
        id: '',
        unitId: '',
        keyWord: ''
      },
      selectedRowKeys: [],
      userpagination: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        showLessItems: true,
        // 修改每页显示条数
        pageSizeOptions: ['5', '10', '20', '30', '50'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      },
      userpaginationList: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        showLessItems: true,
        // 修改每页显示条数
        pageSizeOptions: ['5', '10', '20', '30', '50'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      },
      unitpagination: {
        current: 1,
        total: 0,
        // 默认每页显示10条数据
        pageSize: 10,
        showSizeChanger: true,
        // 修改每页显示条数
        pageSizeOptions: ['10', '20', '50', '100'],
        // 总数据数量
        showTotal: (total) => `共 ${total} 条数据`
      }
    }
  },
  created () { },
  mounted () {
    // this.appUnit()
    // 单位树未被重写时，默认加载单位树
    !this.$slots.unitTree && this.loadUnitTree()
    this.appId = this.$route.query.id
    this.queryParam.id = this.$route.query.id
    this.queryParamList.id = this.$route.query.id
    this.userloadAll()
    this.userloadAllList()
  },
  methods: {
    unitTreeCheck (selectedKeys, info) {
      this.queryParam.secrehUnitId = info.node.dataRef.id
      this.orgId = info.node.dataRef.id
      this.orgType = info.node.dataRef.nodeType

      this.userpagination.current = 1
      this.userpagination.pageSize = 10
      this.userload()
    },
    unitTableRowClick (row) {
      return {
        on: {
          click: () => {
            this.queryParam.secrehUnitId = row.id
            this.queryParam.unitId = row.id
            this.queryParamList.unitId = row.id
            this.orgId = row.id
            this.userload()
            this.userloadAllList()
          }
        }
      }
    },
    findUnit () {
      if (!this.unitNameOrCode) {
        this.showtree = true
        return
      }
      this.showtree = false
      let queryParam = {}
      queryParam.currPage = this.unitpagination.current
      queryParam.pageSize = this.unitpagination.pageSize
      queryParam.name = this.unitNameOrCode
      unitpage(queryParam).then((response) => {
        if (response.list) {
          let i = 0
          for (i; i < response.list.length; i++) {
            const unit = response.list[i]
            for (const item in unit) {
              if (item === 'children') {
                delete unit[item]
              }
            }
          }
        }
        this.unitdata = response.list
        this.unitpagination.current = response.currPage
        this.unitpagination.total = response.totalCount
      })
    },
    loadUnitTree (treeNode) {
      const topId = !treeNode ? 0 : treeNode.dataRef.key
      const _this = this
      return new Promise((resolve) => {
        syncUnitTree(topId).then((response) => {
          if (treeNode) {
            treeNode.dataRef.children = response
            _this.unitTreeData = [..._this.unitTreeData]
            resolve()
          } else {
            _this.unitTreeData = response
          }
        })
      })
    },

    batchSaveStr (id) {
      this.batchSave([id])
    },
    batchSaveList () {
      let id = this.userdata.map((item) => {
        return item.id
      })
      this.batchSave(id)
    },
    batchSave (id) {
      batchSave({
        unitUserIds: id, roleId: this.$route.query.id
      }).then(res => {
        // this.message.success('添加成功')
        this.userload()
        this.getRoleUnitUserListPage()
      })
    },
    batchRemoveStr (id) {
      this.batchRemove([id])
    },
    batchRemoveList () {
      let id = this.userdataList.map((item) => {
        return item.id
      })
      this.batchRemove(id)
    },
    batchRemove (id) {
      batchRemove({
        unitUserIds: id, roleId: this.$route.query.id
      }).then(res => {
        // this.message.success('移除成功')
        this.userload()
        this.getRoleUnitUserListPage()
      })
    },
    onChange (value) {
      const getParentKey = (key, tree) => {
        let parentKey
        for (let i = 0; i < tree.length; i++) {
          const node = tree[i]
          if (node.children) {
            if (node.children.some((item) => item.key === key)) {
              parentKey = node.key
            } else if (getParentKey(key, node.children)) {
              parentKey = getParentKey(key, node.children)
            }
          }
        }
        return parentKey
      }
      this.expandedKeys = []
      let expandedKeys = this.dataList
        .map((item) => {
          if (value.length > 0 && item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.treeDataUnit)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys: expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    onContextMenuClick (item, menuKey) {
      this.getClick(item, menuKey)
      if (menuKey === 'del') {
        this.selectedKeys = []
      }
    },

    onTableSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onTableSelect (record, selected) {
      if (selected) {
        if (this.checkedKeysUnit.checked.indexOf(record.id) === -1) {
          this.checkedKeysUnit.checked.push(record.id)
        }
      }
    },
    onTableSelectAll (selected, selectedRows, changeRows) {
      if (selected) {
        changeRows.forEach((record) => {
          if (this.checkedKeysUnit.checked.indexOf(record.id) === -1) {
            this.checkedKeysUnit.checked.push(record.id)
          }
        })
      }
    },
    userloadAll () {
      // unitByIdUserlist(this.$route.query.id).then((response) => {
      //   this.selectedRowKeys = response
      // })
      this.userpagination.current = 1
      this.userpaginationList.current = 1
      this.userload()
    },
    userloadAllList () {
      this.userpagination.current = 1
      this.userpaginationList.current = 1
      this.getRoleUnitUserListPage()
    },
    getRoleUnitUserListPage () {
      this.queryParamList.currPage = this.userpaginationList.current
      this.queryParamList.pageSize = this.userpaginationList.pageSize
      getRoleUnitUserListPage({ ...this.queryParamList }).then(response => {
        this.userdataList = response.list
        this.userpaginationList.current = response.currPage
        this.userpaginationList.total = response.totalCount
        this.userpaginationList.pageSize = response.pageSize
      })
    },
    userload () {
      this.queryParam.currPage = this.userpagination.current
      this.queryParam.pageSize = this.userpagination.pageSize
      getRoleUnitUserNotInListPage({ ...this.queryParam }).then((response) => {
        this.userdata = response.list
        this.userpagination.current = response.currPage
        this.userpagination.total = response.totalCount
        this.userpagination.pageSize = response.pageSize
      })
    },
    getUserIds () {
      getUserIds({ ...this.queryParam }).then((response) => {
        this.userIds = response
        let selectedRowKeys = this.selectedRowKeys
        this.userIds.map(function (num) {
          selectedRowKeys.splice(selectedRowKeys.indexOf(num), 1)
        })
      })
    },
    userHandleTableChange (userpagination) {
      this.userpagination = userpagination
      this.userload()
    },
    userHandleTableChangeList (userpagination) {
      this.userpaginationList = userpagination
      this.getRoleUnitUserListPage()
    },
    appUnit () {
      let topId
      const loginUser = this.$store.getLoginUser()
      if (loginUser.account === 'admin') {
        topId = 0
      } else {
        topId = loginUser.depts[0].deptId
      }
      this.modalUnitTitle = '机构授权'
      this.checkedKeysUnit.checked = []
      this.expandedKeys = []
      this.treeDataUnit = []
      this.appId = this.$route.query.id
      // this.getCheckedKeys()
      this.initTree(topId)
    },
    initTree (topId) {
      unitTreeByIsTest(this.appId).then((response) => {
        this.treeDataUnit = response
        this.generateList(response)
        this.treeDataUnit.forEach((item) => {
          this.setTreeData(item)
        })
      })
    },
    generateList (data) {
      for (let i = 0; i < data.length; i++) {
        const node = data[i]
        const key = node.key
        this.dataList.push({ key, title: node.treeTitle })
        if (node.children) {
          this.generateList(node.children)
        }
      }
    },
    setTreeData (item) {
      item.scopedSlots = {
        title: 'custom'
      }
      let children = item.children
      if (children && children.length > 0) {
        children.forEach((data) => {
          this.setTreeData(data)
        })
      }
    },
    getCheckedKeys () {
      queryUnit(this.appId).then((response) => {
        if (response.length > 0) {
          response.forEach((item) => {
            // this.expandedKeys.push(item.parentId)
            this.checkedKeysUnit.checked.push(item.id)
          })
        }
      })
    },
    checkUnit (checkedKeys, e) {
      this.checkedKeysUnit.checked = checkedKeys.checked
      // this.queryParam.secrehUnitId = e.node.dataRef.id
      // if (e.checked) {
      //   this.userpagination.current = 1
      //   this.userload()
      // } else {
      //   this.getUserIds()
      // }
    },
    selectUnit (selectedKeys, info) {
      if (selectedKeys.length > 0) {
        let id = selectedKeys[0]
        this.queryParam.secrehUnitId = id
        this.queryParam.unitId = id
        this.queryParamList.unitId = id
        this.userpagination.current = 1
        this.userpaginationList.current = 1
        this.userload()
        this.getRoleUnitUserListPage()
      } else {
        this.queryParam.secrehUnitId = ''
        this.queryParam.unitId = ''
        this.queryParamList.unitId = ''
        this.userpagination.current = 1
        this.userpaginationList.current = 1
        this.userload()
        this.getRoleUnitUserListPage()
      }
      // let id = selectedKeys[0]
      // this.checkedKeysUnit.checked.map(item => {
      //   if (item == id) {
      // this.queryParam.secrehUnitId = id
      // this.userpagination.current = 1
      // this.userload()
      //   }
      // })
      // let selectData = info.node.dataRef
      // if (this.checkedKeysUnit.checked.indexOf(selectData.key) >= 0) {
      //   this.getClick(selectData, 'del')
      //   this.queryParam.secrehUnitId = ''
      // } else {
      //   this.getClick(selectData, 'add')
      //   this.queryParam.secrehUnitId = selectedKeys[0]
      //   this.userload()
      // }
      this.selectedKeys = selectedKeys
    },
    expand (expandedKeys, info) {
      this.autoExpandParent = false
      // let data = info.node.dataRef
      // if (info.expanded) {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'add')
      // } else {
      //   expandedKeys = this.getExpanded(expandedKeys, data, 'del')
      // }

      this.expandedKeys = expandedKeys
    },
    getExpanded (expandedKeys, data, type) {
      if (type === 'add') {
        if (expandedKeys.indexOf(data.key) === -1) {
          expandedKeys.push(data.key)
        }
      } else {
        if (expandedKeys.indexOf(data.key) >= 0) {
          expandedKeys = expandedKeys.filter((k) => k !== data.key)
        }
      }
      let children = data.children
      if (children && children.length > 0) {
        children.forEach((item) => {
          expandedKeys = this.getExpanded(expandedKeys, item, type)
        })
      }
      return expandedKeys
    },
    addClick (item) {
      this.getClick(item, 'add')
    },
    cancelClick (item) {
      this.getClick(item, 'del')
      this.selectedKeys = []
    },
    getClick (data, type) {
      if (type === 'add') {
        if (this.checkedKeysUnit.checked.indexOf(data.key) === -1) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked.push(data.key)
          }
        }
        const addchildren = data.children
        if (addchildren && addchildren.length > 0) {
          for (let i = 0; i < addchildren.length; i++) {
            const addData = addchildren[i]
            this.getClick(addData, 'add')
          }
        }
      } else {
        if (this.checkedKeysUnit.checked.indexOf(data.key) >= 0) {
          if (data.disabled === false) {
            this.checkedKeysUnit.checked = this.checkedKeysUnit.checked.filter(
              (k) => k !== data.key
            )
          }
        }
        const delchildren = data.children
        if (delchildren && delchildren.length > 0) {
          for (let i = 0; i < delchildren.length; i++) {
            const delData = delchildren[i]
            this.getClick(delData, 'del')
          }
        }
      }
    },
    findSearch () {
      if (this.unitSearch) {
        this.showtree = false
      }
      this.showtree = false
      this.unitpagination.currPage = 1
      this.unitpagination.name = this.unitSearch
      this.searchTree()
    },
    searchTree () {
      unitpage(this.unitpagination).then((response) => {
        if (response.list) {
          let i = 0
          for (i; i < response.list.length; i++) {
            const unit = response.list[i]
            for (const item in unit) {
              if (item === 'children') {
                delete unit[item]
              }
            }
          }
        }
        this.unitdata = response.list
        this.unitpagination.current = response.currPage
        this.unitpagination.total = response.totalCount
      })
    },
    searchTableChange (pagination) {
      this.unitpagination = pagination
      this.unitpagination.currPage = pagination.current
      this.unitpagination.name = this.unitSearch
      this.searchTree()
    },
    onSelectChange (selectedRowKeys) {
      this.checkedKeysUnit.checked = selectedRowKeys
    },
    saveUnit () {
      saveUnit(this.$route.query.id, this.selectedRowKeys).then((response) => {
        // this.message.success('保存成功')
        this.$router.go(-1)
      })
    }
  },
  watch: {
    unitSearch (newVal, oldVal) {
      if (newVal == '') {
        this.showtree = true
      }
    }
  }
}
</script>

<style lang="less" scoped>
/deep/.left-role-box {
  /deep/.ant-card-head {
    height: 54px;
    > div {
      line-height: 54px;
    }
  }
}
.border {
  // border: 1px solid #e8e8e8;
  border-bottom: 0;
  border-top: 0;
  border-left: 0;
  margin: 0 5px;
  min-height: 600px;
}
::v-deep .ant-table-wrapper {
  border: 1px solid #e8e8e8;
}
::v-deep .ant-table-body {
  max-height: 500px;
  overflow-y: scroll;
}
.title-box {
  font-size: var(--font-size-18);
  padding-bottom: 10px;
  font-weight: bold;
}
</style>
